import {Component} from '@angular/core';
import {
    AlertController, LoadingController, Modal, ModalController, NavController, NavParams, Platform,
    ToastController
} from 'ionic-angular';
import {TabsPage} from "../tabs/tabs";
import {LoginSettingPage} from "./login-setting/login-setting";
import {LoginPrivacyPage} from "./login-privacy/login-privacy";
import {SystemService} from "../service/SystemService";
import {UserManager} from "../../framework/manager/UserManager";
import {BasePage} from "../BasePage";
import {Log} from "../../framework/utils/Log";
import {WebUrl} from "../../framework/interface/webUrl";
import {SLLocalStorageUtils} from "../../framework/utils/SLLocalStorageUtils";
import {Utils} from "../../framework/utils/Utils";
import {WebSocketClient} from "../../framework/utils/WebSocketClient";

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
    providers: [SystemService]
})
export class LoginPage extends BasePage {

    loginInfo: { loginId ?: string | any, password ?: string | any ,reader ?: boolean | any} = {
        loginId: '',
        password: '',
        reader:false
    };
    loginPhoneInfo: { phoneNumber ?: string | any, code ?: string | any , smsSerialNumber ?: string | any } = {
        phoneNumber: '',
        code: '',
        smsSerialNumber:''
    };
    public server: { ip?: string, port?: string } = {
        ip: WebUrl.ip,
        port: WebUrl.port
    };
    private static TAG: string = 'LoginPage';
    private profileModal:Modal = null;
    sec:any='60';
    backgroundUrl:string;
    loginStyle:{}
    codeText:string='获取验证码';
    loginType:string="0"; //0 密码登录 1 手机号登录
    constructor(public navCtrl: NavController, public navParams: NavParams, public sys: SystemService,
                public platform: Platform,
                public loadingCtrl: LoadingController,
                public modalCtrl: ModalController,
                public toastCtrl: ToastController,
                public alertCtrl: AlertController) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl);
        let data = this.getImageUrl();
        data.then((v) => {
            if (v.msgCode == '1') {
                this.backgroundUrl = v.backgroundImageUrl;
            }
            if (this.backgroundUrl) {
                this.loginStyle = {background:'url('+this.backgroundUrl+') no-repeat'};
            }
        },()=>{

        });
    }

    async getImageUrl() : Promise<any> {
        return await this.sys.getBackgroundImage().toPromise();
    }

    async ionViewDidLoad() {
        Log.w(LoginPage.TAG, 'ionViewDidLoad');
        Utils.getPort();
    }
    login(){
        if(this.loginType ==='0'){
            this.userLogin();
        }else {
            this.phoneLogin();
        }
    }
    changeLogin(id){
        this.loginType =id;
    }
    async mySocket(userId){
        let ip: any = await  SLLocalStorageUtils.getInstance().get_Ip() ||'43.138.239.123';
        let port: any =  await SLLocalStorageUtils.getInstance().get_Port() || '8090';
        const url =`ws://${ip}:${port}/bpm/net/message/${userId}`
         new WebSocketClient(url);
    }
     userLogin() {
        if (!this.loginInfo.reader) {
            this.showError('请阅读并同意《隐私政策》');
            return;
        }
        if (this.loginInfo.loginId === "" || this.loginInfo.password === "") {
            this.showError('用户名或者密码不能为空');
        } else {
            this.showLoading(true, '登录中');
             this.sys.getLoginInfo(this.loginInfo).subscribe((res: any) => {
                if (res.msgCode == '1') {
                    UserManager.getInstance().getUserInfo(res.detail);
                    SLLocalStorageUtils.getInstance().setLoginInfo(this.loginInfo);
                    SLLocalStorageUtils.getInstance().setLoginStatus(true);
                    this.navCtrl.push(TabsPage);
                    let userId = res.detail.YongHuBH;
                    this.mySocket(userId)
                    // 使用方法
                    // console.log(SLLocalStorageUtils.getInstance().get_Ip())
                    //

                } else {
                    this.showError("用户名或密码不正确");
                }
                this.showLoading(false, '')
            }, err => {
                this.showError("网络连接错误");
                this.showLoading(false, '')
            });
        }

    }
    phoneLogin() {
        if(!(/^1[3456789]\d{9}$/.test(this.loginPhoneInfo.phoneNumber))){
            this.showError("手机号码有误");
            return ;
        }
        if (this.loginPhoneInfo.phoneNumber === "" || this.loginPhoneInfo.code === "") {
            this.showError('手机号或者验证码不能为空');
        } else {
            this.showLoading(true, '登录中');
            this.sys.getLoginInfoByPhone(this.loginPhoneInfo).subscribe((res: any) => {
                if (res.msgCode == '1') {
                    UserManager.getInstance().getUserInfo(res.detail);
                    //SLLocalStorageUtils.getInstance().setLoginInfo(this.loginInfo);
                    //SLLocalStorageUtils.getInstance().setLoginStatus(true);
                    this.navCtrl.push(TabsPage);
                } else {
                    this.showError(res.msg);
                }
                this.showLoading(false, '')
            }, err => {
                this.showError("网络连接错误");
                this.showLoading(false, '')
            });
        }

    }
    /*
    * 调用端口设置页面
    * */
    settingHandler() {
        this.profileModal = null;
        //this.navCtrl.push(LoginSettingPage);
        if(this.profileModal) {
            return;
        }
        this.profileModal = this.modalCtrl.create(LoginSettingPage);
        this.profileModal.onDidDismiss(async (data) => {
            this.profileModal = null;
        });
        this.profileModal.present();
    }

    /**
     * 隐私政策
     */
    showContent(){
        if(this.profileModal) {
            return;
        }
        this.profileModal = this.modalCtrl.create(LoginPrivacyPage);
        this.profileModal.onDidDismiss(async (data) => {
            this.profileModal = null;
        });
        this.profileModal.present();
    }

    async getBaseUrl() {
        await this.sys.getSettingInfo().subscribe((res: any) => {
            Log.printObj(LoginPage.TAG, 'data==', res);
            if (res.msgCode === "1") {
            }
        }, error => {
        })
    }
    public flag = 0;
    /*
    * 获取验证码
    * */
    getVerfiyCode(){
        if(this.flag ===1){
            return;
        }
        if(!(/^1[3456789]\d{9}$/.test(this.loginPhoneInfo.phoneNumber))){
            this.showError("手机号码有误");
            return ;
        }
        //this.timerFun();
        this.sys.verifyCodeService(this.loginPhoneInfo).subscribe((res:any)=>{
            if(res.msgCode ==='1'){
                this.loginPhoneInfo.smsSerialNumber = res.smsSerialNumber;
                this.timerFun();
            }else {
                this.showError(res.msg);
            }
        });

    }

    timerFun(){
        this.flag = 1;
        this.sec = this.sec - 1;
        this.codeText = this.sec+"秒后重新发送";
        if (this.sec == 0) {
            this.codeText = "重新发送";

            this.flag = 0;
            this.sec = 60;
            return;
        }
        setTimeout(()=>{
            this.timerFun();
        },1000)
    }

}
